import { defineStore } from 'pinia'

export const useMovieStore = defineStore('movie', {
	state: () => ({
		movies: [],
		categories: [
			{ id: 'all', name: '全部' },
			{ id: 'action', name: '动作' },
			{ id: 'comedy', name: '喜剧' },
			{ id: 'drama', name: '剧情' },
			{ id: 'romance', name: '爱情' },
			{ id: 'sci-fi', name: '科幻' },
			{ id: 'horror', name: '恐怖' },
			{ id: 'animation', name: '动画' }
		],
		banners: [],
		coupons: [],
		recommendMovies: []
	}),

	getters: {
		// 根据分类筛选电影
		getMoviesByCategory: (state) => (categoryId) => {
			if (categoryId === 'all') {
				return state.movies
			}
			return state.movies.filter(movie => movie.category === categoryId)
		},

		// 根据关键词搜索电影
		searchMovies: (state) => (keyword) => {
			if (!keyword.trim()) {
				return state.movies
			}
			return state.movies.filter(movie => 
				movie.title.toLowerCase().includes(keyword.toLowerCase()) ||
				movie.description?.toLowerCase().includes(keyword.toLowerCase())
			)
		},

		// 获取推荐电影（评分高的前5部）
		getRecommendMovies: (state) => {
			return state.movies
				.sort((a, b) => b.rating - a.rating)
				.slice(0, 5)
		}
	},

	actions: {
		// 初始化电影数据
		initMovieData() {
			const movies = uni.getStorageSync('movies')
			if (movies && movies.length > 0) {
				this.movies = movies
			} else {
				// 初始化默认电影数据
				this.movies = [
					{
						id: 1,
						title: '复仇者联盟4：终局之战',
						year: '2019',
						rating: 8.5,
						category: 'action',
						poster: '/static/c1.png',
						description: '漫威电影宇宙的史诗终章，超级英雄们的最终决战。',
						duration: '181分钟',
						director: '罗素兄弟',
						cast: ['小罗伯特·唐尼', '克里斯·埃文斯', '斯嘉丽·约翰逊'],
						createTime: new Date().toISOString()
					},
					{
						id: 2,
						title: '泰坦尼克号',
						year: '1997',
						rating: 9.4,
						category: 'romance',
						poster: '/static/c2.png',
						description: '永恒的爱情经典，跨越阶级的浪漫故事。',
						duration: '194分钟',
						director: '詹姆斯·卡梅隆',
						cast: ['莱昂纳多·迪卡普里奥', '凯特·温斯莱特'],
						createTime: new Date().toISOString()
					},
					{
						id: 3,
						title: '盗梦空间',
						year: '2010',
						rating: 9.3,
						category: 'sci-fi',
						poster: '/static/c3.png',
						description: '诺兰导演的烧脑科幻巨制，梦境与现实的交织。',
						duration: '148分钟',
						director: '克里斯托弗·诺兰',
						cast: ['莱昂纳多·迪卡普里奥', '玛丽昂·歌迪亚'],
						createTime: new Date().toISOString()
					},
					{
						id: 4,
						title: '千与千寻',
						year: '2001',
						rating: 9.4,
						category: 'animation',
						poster: '/static/c4.png',
						description: '宫崎骏的经典动画作品，奇幻的冒险之旅。',
						duration: '125分钟',
						director: '宫崎骏',
						cast: ['柊瑠美', '入野自由'],
						createTime: new Date().toISOString()
					},
					{
						id: 5,
						title: '肖申克的救赎',
						year: '1994',
						rating: 9.7,
						category: 'drama',
						poster: '/static/c5.png',
						description: '关于希望与自由的经典剧情片。',
						duration: '142分钟',
						director: '弗兰克·德拉邦特',
						cast: ['蒂姆·罗宾斯', '摩根·弗里曼'],
						createTime: new Date().toISOString()
					},
					{
						id: 6,
						title: '阿甘正传',
						year: '1994',
						rating: 9.5,
						category: 'drama',
						poster: '/static/c6.png',
						description: '一个简单男人的不平凡人生故事。',
						duration: '142分钟',
						director: '罗伯特·泽米吉斯',
						cast: ['汤姆·汉克斯', '罗宾·怀特'],
						createTime: new Date().toISOString()
					}
				]
				this.saveMoviesToStorage()
			}

			// 初始化轮播图数据
			this.initBannerData()
			// 初始化优惠券数据
			this.initCouponData()
		},

		// 初始化轮播图数据
		initBannerData() {
			// 基于现有电影数据动态生成轮播图
			// 选择前3部电影作为轮播图
			const topMovies = this.movies.slice(0, 3)

			this.banners = topMovies.map(movie => ({
				id: movie.id,
				title: movie.title,
				subtitle: movie.description ? movie.description.substring(0, 20) + '...' : '精彩电影推荐',
				image: movie.poster,
				movieId: movie.id
			}))

			// 如果没有电影，使用默认轮播图
			if (this.banners.length === 0) {
				this.banners = [
					{
						id: 1,
						title: '暂无电影',
						subtitle: '管理员还未添加电影',
						image: '/static/logo.png',
						movieId: null
					}
				]
			}
		},

		// 初始化优惠券数据
		initCouponData() {
			const coupons = uni.getStorageSync('coupons')
			if (coupons && coupons.length > 0) {
				this.coupons = coupons
			} else {
				this.coupons = [
					{
						id: 1,
						amount: '5元',
						description: '新用户专享',
						status: '立即领取',
						type: 'new_user'
					},
					{
						id: 2,
						amount: '10元',
						description: '会员观影券',
						status: '立即领取',
						type: 'member'
					},
					{
						id: 3,
						amount: '15元',
						description: '周末特惠券',
						status: '立即领取',
						type: 'weekend'
					},
					{
						id: 4,
						amount: '20元',
						description: '生日专属券',
						status: '立即领取',
						type: 'birthday'
					}
				]
				uni.setStorageSync('coupons', this.coupons)
			}
		},

		// 添加电影（管理员功能）
		addMovie(movieData) {
			const newMovie = {
				id: this.movies.length > 0 ? Math.max(...this.movies.map(m => m.id)) + 1 : 1,
				...movieData,
				createTime: new Date().toISOString()
			}
			this.movies.push(newMovie)
			this.saveMoviesToStorage()
			// 重新生成轮播图
			this.initBannerData()
			return { success: true, message: '电影添加成功' }
		},

		// 更新电影（管理员功能）
		updateMovie(movieId, movieData) {
			const index = this.movies.findIndex(m => m.id === movieId)
			if (index !== -1) {
				this.movies[index] = { ...this.movies[index], ...movieData }
				this.saveMoviesToStorage()
				// 重新生成轮播图
				this.initBannerData()
				return { success: true, message: '电影更新成功' }
			}
			return { success: false, message: '电影不存在' }
		},

		// 删除电影（管理员功能）
		deleteMovie(movieId) {
			const index = this.movies.findIndex(m => m.id === movieId)
			if (index !== -1) {
				this.movies.splice(index, 1)
				this.saveMoviesToStorage()
				// 重新生成轮播图
				this.initBannerData()
				return { success: true, message: '电影删除成功' }
			}
			return { success: false, message: '电影不存在' }
		},

		// 根据ID获取电影
		getMovieById(movieId) {
			return this.movies.find(m => m.id == movieId)
		},

		// 保存电影数据到本地存储
		saveMoviesToStorage() {
			uni.setStorageSync('movies', this.movies)
		}
	}
})
